﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DTO;
using System.Data.SqlClient;
using System.Data;
using Microsoft.SqlServer.Management.Smo;
using Microsoft.SqlServer.Management.Smo.Agent;
using Microsoft.SqlServer.Management.Common;
using Microsoft.SqlServer.Management;
namespace DAO
{
    public class BACKUP
    {
        public static void makebackup(string BACKUPNAME, Server SQLSERVER)
        {
            bool co = false;
            try
            {
                foreach (BackupDevice backupdevice in SQLSERVER.BackupDevices)
                {
                    if (backupdevice.Name == BACKUPNAME)
                    {
                        co = true;
                        break;
                    }
                }
                if (co == false)
                {
                    BackupDevice newbackupdevice = new BackupDevice();
                    newbackupdevice.Parent = SQLSERVER;
                    newbackupdevice.Name = BACKUPNAME;
                    newbackupdevice.PhysicalLocation = @"D:\" + BACKUPNAME + ".bak";
                    newbackupdevice.BackupDeviceType = BackupDeviceType.Disk;
                    newbackupdevice.Create();
                }
            }
            catch
            {
                return;
            }
        }

        public static bool backup()
        {
            string databasename = "QUAN_LY_THU_VIEN";
            string backupname = "TESTBAKUP";
            try
            {
                ServerConnection serverconn = new ServerConnection();
                serverconn.LoginSecure = true;
                serverconn.ServerInstance = @"(local)\SQLEXPRESS";

                Server sqlserver = new Server(serverconn);

                makebackup(backupname, sqlserver);

                Backup newbackup = new Backup();
                newbackup.Action = BackupActionType.Database;
                newbackup.BackupSetName = databasename + "Back";
                newbackup.Devices.AddDevice(backupname, DeviceType.LogicalDevice);
                newbackup.Database = databasename;

                newbackup.SqlBackup(sqlserver);
                return true;
            }
            catch
            {
                return false;
            }
        }
    }
}
